//
//  BlogViewModel.m
//  CharlesMVX
//
//  Created by Charles on 2020/4/1.
//  Copyright © 2020 Charles. All rights reserved.
//

#import "BlogViewModel.h"

@interface BlogViewModel ()

@property (nonatomic, assign) NSUInteger userId;
@property (nonatomic, strong) UserAPIManager *apiManger;
@property (nonatomic, strong) NSMutableArray<BlogCellViewModel *> *blogs;
@property (nonatomic, strong) RACSignal *refreshDataSignal;
@property (nonatomic, strong) RACSignal *loadMoreDataSignal;

@end

@implementation BlogViewModel

+ (instancetype)viewModelWithUserId:(NSUInteger)userId {
    return [[BlogViewModel alloc]initWithUserId:userId];
}

- (instancetype)initWithUserId:(NSUInteger)userId {
    if (self = [super init]) {
        self.userId = userId;
        self.blogs = [NSMutableArray array];
        self.apiManger = [UserAPIManager new];
        @weakify(self);
        self.refreshDataSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            @strongify(self);
            [self.apiManger refreshUserBlogsWithUserId:self.userId completionHandler:^(NSError *error, id result) {
                if (!error) {
                    [self.blogs removeAllObjects];
                    [self formatResult:result];
                }
                error ? [subscriber sendError:error] : [subscriber sendCompleted];
            }];
            return nil;
        }];
        
        self.loadMoreDataSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            @strongify(self);
            
            [self.apiManger loadModeUserBlogsWithUserId:self.userId completionHandler:^(NSError *error, id result) {
                error ?:[self formatResult:result];
                error ? [subscriber sendError:error] : [subscriber sendCompleted];
            }];
            return nil;
        }];
    }
    return self;
}

- (NSArray<BlogCellViewModel *> *)allDatas {
    return self.blogs;
}

- (void)formatResult:(NSArray *)blogs {
    for (Blog *blog in blogs) {
        [self.blogs addObject:[BlogCellViewModel viewModelWithBlog:blog]];
    }
}

@end
